package com.infore.authorityManagement.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.infore.authorityManagement.entity.SysPermission;
import com.infore.authorityManagement.repository.ISysPermissionRepository;
import com.infore.authorityManagement.service.ISysPermissionService;
import com.infore.authorityManagement.util.Page;
import com.infore.authorityManagement.util.PageUtil;
import com.infore.authorityManagement.util.UUIDGenerator;

/**
 * 权限管理服务层
 * 接口实现类
 * @author cys
 *
 */
@Service
@Transactional
public class SysPermissionServiceImpl implements ISysPermissionService {
    
    @Autowired
    ISysPermissionRepository iSysPermissionRepository;
    
    
    private Specification<SysPermission> createSpecification(SysPermission sysPermission) {
        Specification<SysPermission> specification = new Specification<SysPermission>() {
            @Override
            public Predicate toPredicate(Root<SysPermission> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isBlank(sysPermission.getPermissionName())) {
                    predicates.add(cb.like(root.get("permissionName"), "%"+sysPermission.getPermissionName()+"%"));
                }
                String appCode = sysPermission.getAppCode();
                if (!StringUtils.isBlank(appCode)) {
                    predicates.add(cb.equal(root.get("appCode"), appCode));
                }
                Integer permissionType = sysPermission.getPermissionType();
                if (permissionType != null) {
                    predicates.add(cb.equal(root.get("permissionType"), permissionType));
                }
                Predicate[] p = new Predicate[predicates.size()];
                query.where(cb.and(predicates.toArray(p)));
                query.orderBy(cb.asc(root.get("seqNum")));
                return query.getRestriction();
            }
        };
        return specification;
    }
    
    private Specification<SysPermission> createSpecification2(SysPermission sysPermission) {
        Specification<SysPermission> specification = new Specification<SysPermission>() {
            @Override
            public Predicate toPredicate(Root<SysPermission> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isBlank(sysPermission.getPermissionName())) {
                    predicates.add(cb.equal(root.get("permissionName"), sysPermission.getPermissionName()));
                }
                if (!StringUtils.isBlank(sysPermission.getUrl())) {
                    predicates.add(cb.equal(root.get("url"), sysPermission.getUrl()));
                }
                Integer permissionType = sysPermission.getPermissionType();
                if (permissionType != null) {
                    predicates.add(cb.equal(root.get("permissionType"), permissionType));
                }
                Predicate[] p = new Predicate[predicates.size()];
                query.where(cb.and(predicates.toArray(p)));
                query.orderBy(cb.asc(root.get("seqNum")));
                return query.getRestriction();
            }
        };
        return specification;
    }
    
    @Override
    public List<SysPermission> getPermissions(SysPermission sysPermission) {
        Specification<SysPermission> specification = createSpecification(sysPermission);
        return iSysPermissionRepository.findAll(specification);
    }

    @Override
    public Page<SysPermission> getPermissionsForPage(SysPermission sysPermission, Integer pageNo, Integer pageSize) {
        Specification<SysPermission> specification = createSpecification(sysPermission);
        PageRequest pageable = PageRequest.of(pageNo-1, pageSize);
        return PageUtil.pageConvert(iSysPermissionRepository.findAll(specification, pageable));
    }

    @Override
    public SysPermission getPermissionById(String permissionId) {
        return iSysPermissionRepository.findById(permissionId).orElse(null);
    }

    @Override
    public Map<String, Object> addPermission(SysPermission sysPermission) {
        Map<String, Object> map = new HashMap<String, Object>();
        Specification<SysPermission> specification = createSpecification(sysPermission);
        List<SysPermission> permissionList = iSysPermissionRepository.findAll(specification);

//        if (permissionList.size() > 0 ) {
//            map.put("resultIdt", -1);
//            return map;
//        }
        java.util.Date date = new java.util.Date();
        long d = date.getTime();
        Timestamp timestamp = new Timestamp(d);
        sysPermission.setCreateTime(timestamp);
        String id = UUIDGenerator.getUUID();
        sysPermission.setPermissionId(id);
        sysPermission.setAction(sysPermission.getAction());
        try {
            iSysPermissionRepository.saveAndFlush(sysPermission);
        } catch (Exception ex) {
            map.put("resultIdt", -2);
            return map;
        }
        map.put("resultIdt", 0);
        map.put("permissionId", id);
        return map;
    }

    @Override
    public int updatePermission(SysPermission sysPermission) {

        String permissionName = sysPermission.getPermissionName();
        if (checkPermissionNameExist(sysPermission.getPermissionId(), permissionName)) {
            return -2;
        }
        try {
            SysPermission permission = getPermissionById(sysPermission.getPermissionId());
            if (permissionName != null && !"".equals(permissionName)) {
                permission.setPermissionName(permissionName);
            }
            if (StringUtils.isNotBlank(sysPermission.getAction())) {
                permission.setAction(sysPermission.getAction());
            }
            if (sysPermission.getPermissionType() != null) {
                permission.setPermissionType(sysPermission.getPermissionType());
            }
            if (sysPermission.getDescription() != null && !"".equals(sysPermission.getDescription())) {
                permission.setDescription(sysPermission.getDescription());
            }
            if (sysPermission.getUrl() != null && !"".equals(sysPermission.getUrl())) {
                permission.setUrl(sysPermission.getUrl());
            }
            if (sysPermission.getPermissionLevel() != null) {
                permission.setPermissionLevel(sysPermission.getPermissionLevel());
            }
            if (sysPermission.getSeqNum() != null) {
                permission.setSeqNum(sysPermission.getSeqNum());
            }
            if (StringUtils.isNotBlank(sysPermission.getPermissionPictureUrl())) {
                permission.setPermissionPictureUrl(sysPermission.getPermissionPictureUrl());
            }
            permission.setPermissionParentID(sysPermission.getPermissionParentID());
            if (sysPermission.getPermissionParentID() != null && sysPermission.getPermissionParentID().equals("null")) {
                permission.setPermissionParentID(null);
            }else {
                permission.setPermissionParentID(sysPermission.getPermissionParentID());
            }
            if (sysPermission.getCreateTime() != null) {
                permission.setCreateTime(sysPermission.getCreateTime());
            }
            iSysPermissionRepository.flush();
        } catch (Exception ex) {
            return -3;
        }
        return 0;
    
    }

    private boolean checkPermissionNameExist(String permissionId, String permissionName) {
        SysPermission permission = iSysPermissionRepository.findByPermissionIdNotAndPermissionName
                    (permissionId, permissionName);
        if(permission != null)
            return true;
        return false;
    }

    @Override
    public int deletePermission(String permissionId) {
        SysPermission sysPermission = getPermissionById(permissionId);
        if (sysPermission == null) {
            return -1;
        }
        try {
            if (sysPermission.getPermissionType() == 1) {
                iSysPermissionRepository.deleteAll(iSysPermissionRepository.
                        findByPermissionParentID(permissionId));
            }
           //删除角色用户权限
            
            iSysPermissionRepository.delete(sysPermission);
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  
            return -2;
        }
        return 0;
    }

}
